<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Collections in C#</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="C#, .NET, Mono, collections, programming, language, learn C#">
<meta name="description" content="This part of the C# tutorial covers C# collections.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>


<div class="content">


<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>



<h1>Collections</h1>

<p>
In this chapter we will deal with C# collections.
The .NET framework provides specialized classes for data storage
and retrieval. In one of the previous chapters, we have described 
arrays. Collections are enhancement to the arrays. 
</p>

<p>
There are two distinct collection types in C#. The standard
collections, which are found under the System.Collections namespace and
the generic collections, under System.Collections.Generic. The generic
collections are more flexible and are the preferred way to work with 
data. The generic collections or generics were introduced in 
.NET framework 2.0. Generics enhance code reuse, type safety, 
and performance.
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script>

<p>
<b>Generic programming</b> is a style of computer programming in which algorithms 
are written in terms of to-be-specified-later types that are then
 instantiated when needed for specific types provided as parameters. 
This approach, pioneered by Ada in 1983, permits writing common functions 
or types that differ only in the set of types on which they operate 
when used, thus reducing duplication. (Wikipedia)
</p>

<h2>ArrayList</h2>

<p>
<b class="keyword">ArrayList</b> is a collection from a standard 
System.Collections namespace. It is a dynamic array. It provides random
access to its elements. An ArrayList automatically expands as data
is added. Unlike arrays, an ArrayList can hold data of multiple data types.
Elements in the ArrayList are accessed via an integer index. Indexes
are zero based. Indexing of elements and insertion and deletion at the
end of the ArrayList takes constant time. Inserting or deleting an element
in the middle of the dynamic array is more costly. It takes linear time.
</p>

<pre class="code">
using System;
using System.Collections;

public class CSharpApp 
{
    class Empty
    {}
    
    static void Main()
    {
        ArrayList da = new ArrayList();

        da.Add("Visual Basic");
        da.Add(344);
        da.Add(55);
        da.Add(new Empty());
        da.Remove(55);

        foreach(object el in da)
        {
            Console.WriteLine(el);
        }
    }
}
</pre>

<p>
In the above example, we have created an <code>ArrayList</code> collection.
We have added some elements to it. They are of various data type, string, int
and a class object. 
</p>

<pre class="explanation">
using System.Collections;
</pre>

<p>
In order to work with <code>ArrayList</code> collection, we need
to import <code>System.Collections</code> namespace.
</p>

<pre class="explanation">
ArrayList da = new ArrayList();
</pre>

<p>
An <code>ArrayList</code> collection is created.
</p>

<pre class="explanation">
da.Add("Visual Basic");
da.Add(344);
da.Add(55);
da.Add(new Empty());
da.Remove(55);
</pre>

<p>
We add five elements to the array with the <code>Add()</code> method.
</p>

<pre class="explanation">
da.Remove(55);
</pre>

<p>
We remove one element. 
</p>

<pre class="explanation">
foreach(object el in da)
{
    Console.WriteLine(el);
}
</pre>

<p>
We iterate through the array and print its elements
to the console. 
</p>

<pre>
$ ./arraylist.exe 
Visual Basic
344
CSharpApp+Empty
</pre>

<p>
Output.
</p>

<h2>List</h2>

<p>
A <code>List</code> is a strongly typed list of objects that 
can be accessed by index. It can be found under System.Collections.Generic
namespace. 
</p>

<pre class="code">
using System;
using System.Collections.Generic;

public class CSharpApp 
{

    static void Main()
    {
        List&lt;string&gt; langs = new List&lt;string&gt;();

        langs.Add("Java");
        langs.Add("C#");
        langs.Add("C");
        langs.Add("C++");
        langs.Add("Ruby");
        langs.Add("Javascript");

        Console.WriteLine(langs.Contains("C#"));

        Console.WriteLine(langs[1]);
        Console.WriteLine(langs[2]);

        langs.Remove("C#");
        langs.Remove("C");

        Console.WriteLine(langs.Contains("C#"));

        langs.Insert(4, "Haskell");

        langs.Sort();

        foreach(string lang in langs)
        {
            Console.WriteLine(lang);
        }
     
    }
}
</pre>

<p>
In the preceding example, we work with the <code>List</code>  
collection.
</p>

<pre class="explanation">
using System.Collections.Generic;
</pre>

<p>
In order to work with the <code>List</code> collection,
we need to import the <code>System.Collections.Generic</code>
namespace.
</p>

<pre class="explanation">
List&lt;string&gt; langs = new List&lt;string&gt;();
</pre>

<p>
A generic dynamic array is created. We specify that we will work
with strings with the type specified inside &lt;&gt; characters.
</p>

<pre class="explanation">
langs.Add("Java");
langs.Add("C#");
langs.Add("C");
...
</pre>

<p>
We add elements to the List using the <code>Add()</code> method.
</p>

<pre class="explanation">
Console.WriteLine(langs.Contains("C#"));
</pre>

<p>
We check if the List contains a specific string using the 
<code>Contains()</code> method.
</p>

<pre class="explanation">
Console.WriteLine(langs[1]);
Console.WriteLine(langs[2]);
</pre>

<p>
We access the second and the third element of the List
using the index notation.
</p>

<pre class="explanation">
langs.Remove("C#");
langs.Remove("C");
</pre>

<p>
We remove two strings from the List.
</p>

<pre class="explanation">
langs.Insert(4, "Haskell");
</pre>

<p>
We insert a string at a specific location.
</p>

<pre class="explanation">
langs.Sort();
</pre>

<p>
We sort the elements using the <code>Sort()</code>
method.
</p>

<pre>
$ ./list.exe 
True
C#
C
False
C++
Haskell
Java
Javascript
Ruby
</pre>

<p>
Outcome of the example.
</p>

<h2>LinkedList</h2>

<p>
<code>LinkedList</code> is a generic doubly linked list in C#. LinkedList only 
allows sequential access. LinkedList allows for constant-time insertions
or removals, but only sequential access of elements. Because linked lists need
extra storage for references, they are impractical for lists of small data items
such as characters. Unlike dynamic arrays, arbitrary number of items can be added
to the linked list (limited by the memory of course) without the need to realocate, 
which is an expensive operation.
</p>

<pre class="code">
using System;
using System.Collections.Generic;

public class CSharpApp 
{

    static void Main()
    {
        LinkedList&lt;int&gt; nums = new LinkedList&lt;int&gt;();

        nums.AddLast(23);
        nums.AddLast(34);
        nums.AddLast(33);
        nums.AddLast(11);
        nums.AddLast(6);
        nums.AddFirst(9);
        nums.AddFirst(7);

        LinkedListNode&lt;int&gt; node = nums.Find(6);
        nums.AddBefore(node, 5);

        foreach(int num in nums)
        {
            Console.WriteLine(num);
        }
    }
}
</pre>

<p>
This is a <code>LinkedList</code> example with some of its methods.
</p>

<pre class="explanation">
LinkedList&lt;int&gt; nums = new LinkedList&lt;int&gt;();
</pre>

<p>
This is an integer <code>LinkedList</code>.
</p>

<pre class="explanation">
nums.AddLast(23);
...
nums.AddFirst(7);
</pre>

<p>
We populate the linked list using the <code>AddLast()</code>
and <code>AddFirst()</code> methods.
</p>

<pre class="explanation">
LinkedListNode&lt;int&gt; node = nums.Find(6);
nums.AddBefore(node, 5);
</pre>

<p>
A <code>LinkedList</code> consists of nodes. We find a specific 
node and add an element before it. 
</p>

<pre class="explanation">
foreach(int num in nums)
{
    Console.WriteLine(num);
}
</pre>

<p>
Printing all elements to the console. 
</p>

<h2>Dictionary</h2>

<p>
A <b class="keyword">dictionary</b>, also called an associative array, is a collection 
of unique keys and a collection of values, where each key is associated with one value.
Retrieving and adding values is very fast. Dictionaries take more memory, because
for each value there is also a key.
</p>

<pre class="code">
using System;
using System.Collections.Generic;


public class CSharpApp 
{
    static void Main()
    {
        Dictionary&lt;string, string&gt; domains = new Dictionary&lt;string, string&gt;();

        domains.Add("de", "Germany");
        domains.Add("sk", "Slovakia");
        domains.Add("us", "United States");
        domains.Add("ru", "Russia");
        domains.Add("hu", "Hungary");
        domains.Add("pl", "Poland");

        Console.WriteLine(domains["sk"]);
        Console.WriteLine(domains["de"]);

        Console.WriteLine("Dictionary has {0} items",
            domains.Count);

        Console.WriteLine("Keys of the dictionary:");

        List&lt;string&gt; keys = new List&lt;string&gt;(domains.Keys);

        foreach(string key in keys)
        {
            Console.WriteLine("{0}", key);
        }        

        Console.WriteLine("Values of the dictionary:");

        List&lt;string&gt; vals = new List&lt;string&gt;(domains.Values);

        foreach(string val in vals)
        {
            Console.WriteLine("{0}", val);
        }

        Console.WriteLine("Keys and values of the dictionary:");


        foreach(KeyValuePair&lt;string, string&gt; kvp in domains)
        {
            Console.WriteLine("Key = {0}, Value = {1}", 
                kvp.Key, kvp.Value);
        }
    }
}
</pre>

<p>
We have a dictionary, where we map domain names to their country names.
</p>

<pre class="explanation">
Dictionary&lt;string, string&gt; domains = new Dictionary&lt;string, string&gt;();
</pre>

<p>
We create a dictionary with string keys and values. 
</p>

<pre class="explanation">
domains.Add("de", "Germany");
domains.Add("sk", "Slovakia");
domains.Add("us", "United States");
...
</pre>

<p>
We add some data to the dictionary. The first string is the key.
The second is the value.
</p>

<pre class="explanation">
Console.WriteLine(domains["sk"]);
Console.WriteLine(domains["de"]);
</pre>

<p>
Here we retrieve two values by their keys. 
</p>

<pre class="explanation">
Console.WriteLine("Dictionary has {0} items",
    domains.Count);
</pre>

<p>
We print the number of items by referring to the 
<code>Count</code> property.
</p>

<pre class="explanation">
List&lt;string&gt; keys = new List&lt;string&gt;(domains.Keys);

foreach(string key in keys)
{
    Console.WriteLine("{0}", key);
}  
</pre>

<p>
These lines retrieve all keys from the dictionary.
</p>

<pre class="explanation">
List&lt;string&gt; vals = new List&lt;string&gt;(domains.Values);

foreach(string val in vals)
{
    Console.WriteLine("{0}", val);
}
</pre>

<p>
These lines retrieve all values from the dictionary.
</p>

<pre class="explanation">
foreach(KeyValuePair&lt;string, string&gt; kvp in domains)
{
    Console.WriteLine("Key = {0}, Value = {1}", 
        kvp.Key, kvp.Value);
}
</pre>

<p>
Finally, we print both keys and values of the dictionary.
</p>

<pre>
$ ./dictionary.exe 
Slovakia
Germany
Dictionary has 6 items
Keys of the dictionary:
de
sk
us
ru
hu
pl
Values of the dictionary:
Germany
Slovakia
United States
Russia
Hungary
Poland
Keys and values of the dictionary:
Key = de, Value = Germany
Key = sk, Value = Slovakia
Key = us, Value = United States
Key = ru, Value = Russia
Key = hu, Value = Hungary
Key = pl, Value = Poland
</pre>

<p>
This is the output of the example. 
</p>

<h2>Queues</h2>

<p>
A <code>queue</code> is a First-In-First-Out (FIFO) data structure. 
The first element added to the queue will be the first one to be 
removed. Queues may be used to process messages as they appear or 
serve customers as they come. The first customer which comes should 
be served first. 
</p>

<pre class="code">
using System;
using System.Collections.Generic;


public class CSharpApp 
{
    static void Main()
    {
        Queue&lt;string&gt; msgs = new Queue&lt;string&gt;();

        msgs.Enqueue("Message 1");
        msgs.Enqueue("Message 2");
        msgs.Enqueue("Message 3");
        msgs.Enqueue("Message 4");
        msgs.Enqueue("Message 5");

        Console.WriteLine(msgs.Dequeue());
        Console.WriteLine(msgs.Peek());
        Console.WriteLine(msgs.Peek());

        Console.WriteLine();

        foreach(string msg in msgs)
        {
            Console.WriteLine(msg);
        }
    }
}
</pre>

<p>
In our example, we have a queue with messages.
</p>

<pre class="explanation">
Queue&lt;string&gt; msgs = new Queue&lt;string&gt;();
</pre>

<p>
A queue of strings is created.
</p>

<pre class="explanation">
msgs.Enqueue("Message 1");
msgs.Enqueue("Message 2");
...
</pre>

<p>
The <code>Enqueue()</code> adds a message to the 
end of the queue. 
</p>

<pre class="explanation">
Console.WriteLine(msgs.Dequeue());
</pre>

<p>
The <code>Dequeue()</code> method removes and returns the
item at the beginning of the queue.
</p>

<pre class="explanation">
Console.WriteLine(msgs.Peek());
</pre>

<p>
The <code>Peek()</code> method returns the next item from
the queue, but does not remove it from the collection.
</p>

<pre>
$ ./queue.exe 
Message 1
Message 2
Message 2

Message 2
Message 3
Message 4
Message 5
</pre>

<p>
The <code>Dequeue()</code> method removes the "Message 1" from
the collection. The <code>Peek()</code> method does not. The 
"Message 2" remains in the collection.
</p>


<h2>Stacks</h2>

<p>
A <b class="keyword">stack</b> is a Last-In-First-Out (LIFO) data structure. 
The last element added to the queue will be the first one to be removed. 
The C language uses a stack to store local data in a function. The stack
is also used when implementing calculators.
</p>

<pre class="code">
using System;
using System.Collections.Generic;


public class CSharpApp 
{
    static void Main()
    {
        Stack&lt;int&gt; stc = new Stack&lt;int&gt;();

        stc.Push(1);
        stc.Push(4);
        stc.Push(3);
        stc.Push(6);
        stc.Push(4);

        Console.WriteLine(stc.Pop());
        Console.WriteLine(stc.Peek());
        Console.WriteLine(stc.Peek());

        Console.WriteLine();

        foreach(int item in stc)
        {
            Console.WriteLine(item);
        }
    }
}
</pre>

<p>
We have a simple stack example above.
</p>

<pre class="explanation">
Stack&lt;int&gt; stc = new Stack&lt;int&gt;();
</pre>

<p>
A <code>Stack</code> data structure is created.
</p>

<pre class="explanation">
stc.Push(1);
stc.Push(4);
...
</pre>

<p>
The <code>Push()</code> method adds an item at
the top of the stack.
</p>


<pre class="explanation">
Console.WriteLine(stc.Pop());
</pre>

<p>
The <code>Pop()</code> method removes and
returns the item from the top of the stack.
</p>

<pre class="explanation">
Console.WriteLine(stc.Peek());
</pre>

<p>
The <code>Peek()</code> method returns the item 
from the top of the stack. It does not remove it.
</p>

<pre>
$ ./stack.exe 
4
6
6

6
3
4
1
</pre>

<p>
Output.
</p>


<p>
This part of the C# tutorial was dedicated to Collections in C#. 
</p>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified October 16, 2010  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

